package com.newworld.dmsapp2.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.util.Config;

public class WebViewMainActivity extends Activity {

	private static final String URL = "http://www.pgyer.com/NewWorldApp";

	private WebView wvShow;
	private ProgressBar pbLoading;
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 更新进度条 */
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数量 */
	private int progress;
	// 软件名
	private String appName = "DmsApp2.apk";
	// 更新版本号
	private String updateVersionCode;
	private String updateUrl;
	private Intent intent;
	private Bundle bundle;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// 安装文件
				installApk();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_webview);
		intent = getIntent();
		bundle = intent.getExtras();
		updateUrl = bundle.getString(Config.APP_UPDATEURL);
		updateVersionCode = bundle.getString(Config.APP_UPDATE_VERSIONCODE);
		wvShow = (WebView) findViewById(R.id.web_view);
		pbLoading = (ProgressBar) findViewById(R.id.pb_loading);

		wvShow.setDownloadListener(new DownloadListener() {

			@Override
			public void onDownloadStart(String url, String userAgent,
					String contentDisposition, String mimetype,
					long contentLength) {
				// 监听下载功能，当用户点击下载链接的时候，直接调用系统的浏览器来下载
				// showDownloadDialog();
				checkUpdate();
				/*
				 * Uri uri = Uri.parse(url); Intent intent = new
				 * Intent(Intent.ACTION_VIEW, uri); startActivity(intent);
				 */
			}
		});

		wvShow.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageFinished(WebView view, String url) {
				// 页面加载完毕
				super.onPageFinished(view, url);
				if (pbLoading != null
						&& pbLoading.getVisibility() == View.VISIBLE) {
					pbLoading.setVisibility(View.GONE);// 进度条不可见
				}
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// 页面开始加载
				super.onPageStarted(view, url, favicon);
				if (pbLoading != null
						&& pbLoading.getVisibility() == View.INVISIBLE) {
					pbLoading.setVisibility(View.VISIBLE);// 进度条可见
				}
			}

		});

		wvShow.getSettings().setJavaScriptEnabled(true);// 设置支持脚本
		wvShow.getSettings().setBuiltInZoomControls(true);// 设置支持缩放
		wvShow.getSettings().setDefaultZoom(ZoomDensity.FAR);// 屏幕自适应网页,如果没有这个，在低分辨率的手机上显示可能会异常
		wvShow.loadUrl(URL);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		return true;

	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		//MenuInflater inflater = getMenuInflater();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.refresh: {// 刷新

			wvShow.loadUrl(URL);
			break;
		}
		case R.id.open_in_brower: {// 在浏览器中打开
			showDownloadDialog();
			break;
		}
		}
		return true;
	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate() {

		if (isUpdate()) {
			Log.e("版本更新", "更新版本号不必强制更新");
			showDownloadDialog();
		} else {
			Log.e("版本更新", "更新版本号不必强制更新");
			Toast.makeText(WebViewMainActivity.this, "当前版本已是最新版本",
					Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	private boolean isUpdate() {
		boolean flag = false;
		// 获取当前软件版本
		int versionCode = 0;
		try {
			versionCode = getVersionCode();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		int serviceCode = Integer.valueOf(updateVersionCode);
		// 版本判断
		if (serviceCode > versionCode) {
			flag = true;
		} else {
			flag = false;
		}
		return flag;
	}

	/**
	 * 获取软件版本号
	 * 
	 * @param context
	 * @return
	 */
	private int getVersionCode() throws Exception {
		// 获取packagemanager的实例
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(),
				0);
		int version = packInfo.versionCode;
		return version;
	}

	/**
	 * 显示软件下载对话框
	 */
	private void showDownloadDialog() {
		// 构造软件下载对话框
		AlertDialog.Builder builder = new Builder(WebViewMainActivity.this);
		builder.setTitle(R.string.soft_updating);
		// 给下载对话框增加进度条
		final LayoutInflater inflater = LayoutInflater
				.from(WebViewMainActivity.this);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton(R.string.soft_update_cancel,
				new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						// 设置取消状态
						cancelUpdate = true;
					}
				});
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		// 现在文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk() {
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 * @date 2012-4-26
	 * @blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread {
		@Override
		public void run() {
			try {
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// 获得存储卡的路径
					String sdpath = Environment.getExternalStorageDirectory()
							+ "/";
					mSavePath = sdpath + "download";
					URL url = new URL(updateUrl);
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入流
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists()) {
						file.mkdir();
					}
					File apkFile = new File(mSavePath, appName);
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do {
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0) {
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载.
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk() {
		File apkfile = new File(mSavePath, appName);
		if (!apkfile.exists()) {
			return;
		}
		// 通过Intent安装APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		startActivity(i);
	}

}